import { findUser } from '../service/UserService.js'
import bcrypt from 'bcryptjs'
//验证中间件
export const UserEmptyValidate = () => async (ctx, next) => {
  const { username, password, phone } = ctx.request.body

  //注册
  if (!username || !password) {
    ctx.fail(400, '用户名或密码不能为空')
    return
  }
  //继续操作
  await next();
}

export const UserVerifyValidate = () => async (ctx, next) => {
  const { username } = ctx.request.body

  //查询用户名是否存在
  const user = await findUser({ username })

  if (user) {
    //ctx.body = { code: 400, msg: '用户名已存在' }
    ctx.fail(400, '用户名已存在')
    return;
  }

  await next();
}

export const UserPasswordValidate = () => async (ctx, next) => {
  const { password } = ctx.request.body

  //密码长度
  if (password.length < 6) {
    ctx.fail(400, '密码长度不能小于6位')
    return;
  }

  const salt = await bcrypt.genSaltSync(10);
  //hash
  const hash = await bcrypt.hashSync(password, salt);

  ctx.request.body.password = hash;

  await next();
}
